import React, {useEffect, useState} from 'react';
import { useHistory } from "react-router-dom";

import {List, DatePicker, Toast, TextareaItem, Picker, PickerView} from 'antd-mobile';
import Btn from "../../../components/btn/Btn";
import UserMsg from "../../outUser/userMsg/UserMsg";

import './edit.less'
import http from "../../../model/http";
import ListCheckbox from "../../../components/listCheckbox/ListCheckbox";
import {dateFormat, sendMsg} from '../../../model/code';
import { asap } from 'rxjs';
import Header from "../../../components/header/Header";
import { useForm } from 'react-hook-form';
const Item = List.Item;

function Edit() {
  const history = useHistory();
  const nowTimeStamp = new Date();

  const [date,setDate] = useState(nowTimeStamp);
  const [time,setTime] = useState(nowTimeStamp);

  const [items,setItems] = useState([]);
  const [showItems,setShowItems] = useState(false);
  // 备注
  const [mark,setMark] = useState('')

  // 咨询
  const [consulting,setConsulting] = useState('')

  
   
  const [ expertsData, setExpertsData ] = useState([])

  const [ expertValue, setExpertValue ] = useState([])   
  
  const [ expertIdVal, setExpertIdVal ] = useState('') 
  useEffect(()=>{
    console.log(history.location.state)
    // http.post('/customer/consultItemsList').then(e=>{
    //   setItems(e.data.map(i=>{i.value=i.id;i.label=i.name;i.checked=false;return i}))
    // })
    http.get('/expert/list',{
      hosId: window.localStorage.getItem("hosId") || window.hos.hosId,
    }).then(res => {
      console.log('res数据：',res)
      if(res.code == '0'){
        setExpertsData(res.data)
      }
    })
  },[])


  const selectItems = (_items)=>{
    setItems(_items)
  }

  const submit = async ()=>{
      const _d = {
        customerCrmId:history.location.state.customerCrmId,
        daoyuandate:dateFormat(date,'yyyy-MM-dd'),
        daoyuantime:dateFormat(time,'hh:mm'),
        // consultitemClassId:items.filter(v=>v.checked).map(v=>v.value).join(),

        
        // 顾客姓名
        customerCrmName: history.location.state.customerName,
        //咨询项目内容
        consultContent: consulting.replace(/\s*/g, ''),
        // 所属客管，现场
        zx_name: history.location.state.xcname,
        // 备注信息
        memo: mark,
        // 专家ID
        expertId: (expertIdVal !='' ? expertIdVal.match(/(\S*)-/)[1] : ''),
        // 专家Value
        expertName: (expertIdVal != '' ? expertIdVal.match(/-(\S*)/)[1] : ''),
        // 卡号
        customerCardNo: history.location.state.mzcode
      };
      if(!_d.consultContent){Toast.fail('请输入要咨询的项目');return ;}
      const order = await http.post('/customer/addConsult',_d);

      const user = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {}
      
       console.log(user)
      // const link = `${window.location.origin}/outUser/yuyue?hosId=${window.hos.hosId}&crmId=${_d.customerCrmId}&orderId=${order.yuyueid}&managerId=${user.managerId}`;
      // console.log('link',link)
      // sendMsg(link,'预约咨询','待确认');
      
      if(order.result == 0){
        Toast.success(order.message) 
        setTimeout(() => {
          history.push('/yuyue') 
        }, 500); 
      }else{
        Toast.fail(order.message) 
      }

      
  }
  const prospectiveChange = async (v) => {
    
    console.log(v) 
    setExpertValue(v)  
    
    setExpertIdVal(v[1]) 
  } 
 

  return (
    <div className='v-yuyue-edit'>
      <div className='body-background-div'></div>
      <UserMsg msg={history.location.state} />

      <List className='g-mb10 g-p5-10 g-bg-f g-bdrs12'>
        <DatePicker mode="date" value={date}
                    minDate={nowTimeStamp} onChange={d=>{setDate(d)}}>
          <Item arrow="horizontal">到院日期</Item>
        </DatePicker>
        <DatePicker mode="time" value={time} minDate={nowTimeStamp}
                    nowTimeStamp={nowTimeStamp} onChange={d=>{setTime(d)}}>
          <Item arrow="horizontal">到院时间</Item>
        </DatePicker> 

        <Picker
          cols={2} 
          title="意向专家"
          extra="请选择(可选)"
          data={expertsData}
          value={expertValue} 
          onChange={(v) => prospectiveChange(v)}
         
        >
          <Item arrow="horizontal">意向专家</Item>
        </Picker>

        {/* <Item extra={items.filter(v=>v.checked).map(v=>v.label).join() || '请选择'}
              arrow='horizontal' wrap multipleLine
              onClick={()=>{setShowItems(true)}}>
          意向专家
        </Item> */}

        
      </List>


      <List className='g-mb30 g-p5-10 g-bg-f g-bdrs12'>
        <TextareaItem value={consulting} rows={5} count={100} onChange={setConsulting} placeholder='请输入咨询项目...'/>
      </List>


      <List className='g-mb30 g-p5-10 g-bg-f g-bdrs12'>
        <TextareaItem value={mark} rows={5} count={100} onChange={setMark} placeholder='请输入备注信息...'/>
      </List>
      {/* <Btn type='primary' onClick={submit}>确定并发送给顾客</Btn> */}
      <Btn type='primary' onClick={submit}>保存并提交</Btn>

      <ListCheckbox data={items} visible={showItems} setVisible={setShowItems} afterClose={selectItems}/>

      <Header />
    </div>

  )

}

export default Edit;


/*
// 车牌-键盘
import LicenseKeyboard from 'vehicle-plate-keyboard';
import 'vehicle-plate-keyboard/dist/main.css';

  const [cart,setCart] = useState(false);
  const [key,setKey] = useState({show:false,value:''})
        isCar:cart?1:0,
        carNo:cart?key.value:''

  const clearKey = ()=>{
    setKey({value:key.value,show:false})
  }

<Item extra={
          <Switch checked={cart} color='#108ee9'
                  onChange={()=>{cart&&setKey({value:'',show:false});setCart(!cart)}}/>
        }>是否开车</Item>
<Item extra={key.value} onClick={()=>{cart && setKey({value:key.value,show:true})}}>车牌号</Item>


<Modal popup animationType='slide-up'
             visible={key.show} onClose={clearKey}>
        <LicenseKeyboard
            confirmButtonStyle={{width:'100%',padding:'0 14px',display:'flex',justifyContent:'space-between'}}
            confirmButtonText={<>
              <span onClick={clearKey}>取消</span>
              <span style={{color:'#F26926'}}>{key.value}</span>
              <span onClick={clearKey}>确认</span>
            </>}
            visible={key.show}
            onChange={value =>{setKey({show:true,value:value})}}
            value={key.value}
            done={clearKey}
        />
      </Modal>

 */